package com.powernode.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powernode.domain.SysRole;
import com.powernode.model.Result;
import com.powernode.service.SysRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 系统角色业务控制层
 */
@Api(tags = "系统角色接口管理")
@RequestMapping("sys/role")
@RestController
public class SysRoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @ApiOperation("查询系统角色集合")
    @GetMapping("list")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public Result<List<SysRole>> loadSysRoleList() {
        List<SysRole> sysRoles = sysRoleService.querySysRoleList();
        return Result.success(sysRoles);
    }

    @ApiOperation("多条件分页查询角色")
    @GetMapping("page")
    @PreAuthorize("hasAuthority('sys:role:page')")
    public Result<Page<SysRole>> loadSysRolePage(Page<SysRole> page,String roleName) {
        page = sysRoleService.page(page,new LambdaQueryWrapper<SysRole>()
                .like(StringUtils.hasText(roleName),SysRole::getRoleName,roleName)
                .orderByDesc(SysRole::getCreateTime)
        );
        return Result.success(page);
    }

    @ApiOperation("新增角色")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:role:save')")
    public Result<String> addSysRole(@RequestBody SysRole sysRole) {
        Integer count = sysRoleService.addSysRole(sysRole);
        return Result.handle(count>0);
    }

//    sys/role/info/4
    @ApiOperation("查询角色详情")
    @GetMapping("info/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:info')")
    public Result<SysRole> loadSysRoleInfo(@PathVariable Long roleId) {
        SysRole sysRole = sysRoleService.querySysRoleInfoById(roleId);
        return Result.success(sysRole);
    }

    @ApiOperation("修改角色信息")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result<String> modifySysRole(@RequestBody SysRole sysRole) {
        Boolean flag = sysRoleService.modifySysRole(sysRole);
        return Result.handle(flag);
    }

    @ApiOperation("批量删除角色")
    @DeleteMapping
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public Result<String> removeSysRole(@RequestBody List<Long> roleIds) {
        Boolean flag = sysRoleService.removeSysRolesByIdList(roleIds);
        return Result.handle(flag);
    }
}
